/**
 * API配置和拦截器设置
 */

import axios from 'axios'
import { ElMessage } from 'element-plus'

// API基础配置
export const API_CONFIG = {
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
}

// 创建axios实例
export const apiClient = axios.create(API_CONFIG)

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = localStorage.getItem('auth_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    // 添加租户ID
    const tenantId = localStorage.getItem('tenant_id')
    if (tenantId) {
      config.headers['X-Tenant-Id'] = tenantId
    }

    // 添加请求ID用于追踪
    config.headers['X-Request-ID'] = generateRequestId()

    console.log(`🚀 API Request: ${config.method?.toUpperCase()} ${config.url}`, {
      headers: config.headers,
      data: config.data
    })

    return config
  },
  (error) => {
    console.error('❌ Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    console.log(`✅ API Response: ${response.config.method?.toUpperCase()} ${response.config.url}`, {
      status: response.status,
      data: response.data
    })

    // ABP格式响应处理
    if (response.data && typeof response.data === 'object') {
      // 检查是否是ABP响应格式
      if ('success' in response.data || 'result' in response.data || 'error' in response.data) {
        if (!response.data.success && response.data.error) {
          // ABP错误处理
          handleAbpError(response.data.error)
          return Promise.reject(new Error(response.data.error.message || '请求失败'))
        }
        // 返回ABP响应的result部分
        return response.data.result !== undefined ? response.data.result : response.data
      }
    }

    return response.data
  },
  (error) => {
    console.error(`❌ API Error: ${error.config?.method?.toUpperCase()} ${error.config?.url}`, error)

    // 处理HTTP错误状态码
    if (error.response) {
      const { status, data } = error.response

      switch (status) {
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          // 跳转到登录页面
          localStorage.removeItem('auth_token')
          localStorage.removeItem('user_info')
          window.location.href = '/login'
          break
        case 403:
          ElMessage.error('没有权限执行此操作')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 422:
          // 验证错误
          if (data.errors) {
            const errorMessages = Object.values(data.errors).flat()
            ElMessage.error(errorMessages.join('; '))
          } else {
            ElMessage.error(data.message || '请求参数有误')
          }
          break
        case 500:
          ElMessage.error('服务器内部错误，请稍后重试')
          break
        default:
          ElMessage.error(data?.message || `请求失败 (${status})`)
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error('网络连接失败，请检查网络设置')
    } else {
      // 请求配置错误
      ElMessage.error('请求配置错误')
    }

    return Promise.reject(error)
  }
)

// 生成请求ID
function generateRequestId(): string {
  return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 处理ABP错误
function handleAbpError(error: any) {
  if (typeof error === 'string') {
    ElMessage.error(error)
  } else if (error.message) {
    ElMessage.error(error.message)
  } else if (error.details) {
    ElMessage.error(error.details)
  } else {
    ElMessage.error('请求失败，请稍后重试')
  }
}

// ABP响应类型定义
export interface AbpResponse<T = any> {
  success: boolean
  result?: T
  error?: {
    code: string
    message: string
    details?: string
    validationErrors?: { message: string }[]
  }
  targetUrl?: string
}

export interface AbpQueryResult<T = any> {
  items: T[]
  totalCount: number
}

// API响应包装器
export class ApiResponse<T = any> {
  constructor(
    public data: T,
    public success: boolean = true,
    public message: string = ''
  ) {}

  static success<T>(data: T, message = ''): ApiResponse<T> {
    return new ApiResponse(data, true, message)
  }

  static error(message: string): ApiResponse<null> {
    return new ApiResponse(null, false, message)
  }
}

// 导出默认实例
export default apiClient